package com.rongshu.view.submitArticle.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.rongshu.R;
import com.rongshu.utils.Constant;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.submitArticle.adapter.PostArticleImgAdapter;
import com.rongshu.view.submitArticle.listener.MyCallBack;
import com.rongshu.view.submitArticle.listener.OnRecyclerItemClickListener;
import com.rongshu.view.submitArticle.presenter.SubmitPostPresenter;
import com.rongshu.view.submitArticle.view.SubmitPostView;
import com.utils.LogUtil;
import com.utils.SPUtils;
import com.utils.constants.SPKey;
import com.widget.titlebar.ImmersionBar;
import com.widget.toast.ToastUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * created by zhengweis on 2018/11/8.
 * description：发帖
 */
public class SubmitPostActivity extends BaseActivity<SubmitPostPresenter> implements SubmitPostView {
    @BindView(R.id.content_length)
    TextView contentLength;
    @BindView(R.id.article_title)
    EditText articleTitle;
    @BindView(R.id.article_content)
    EditText articleContent;
    @BindView(R.id.article_title_layout)
    RelativeLayout articleTitleLayout;
    @BindView(R.id.picture_list)
    RecyclerView pictureList;
    @BindView(R.id.hint_layout)
    LinearLayout hintLayout;
    @BindView(R.id.add_post_title)
    TextView addPostTitle;

    private PostArticleImgAdapter postArticleImgAdapter;
    private ItemTouchHelper itemTouchHelper;
    private int penpalId;
    private ArrayList<String> pictrues;
    public int IMAGE_SIZE = 9;//最多可以上传9张图片
    public int REQUEST_PICTURE_CODE = 1011;//获取相册图片
    private String initialTitle, initialContent;
    private boolean showArticleTitle = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar bar = ImmersionBar.with(this);
        bar.reset().keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (ImmersionBar.isSupportStatusBarDarkFont()) {//是否支持修改状态栏字体颜色
            bar.transparentStatusBar()  //透明状态栏，不写默认透明色
                    .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.color_2c2c2c)  //修改flyme OS状态栏字体颜色
                    .statusBarAlpha(0);
        } else {
            bar.transparentStatusBar()  //透明状态栏，不写默认透明色
                    .flymeOSStatusBarFontColor(R.color.black)  //修改flyme OS状态栏字体颜色
                    //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                    .statusBarDarkFont(true, 1.0f);
        }
        bar.init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_submit_post;
    }

    @Override
    protected void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            penpalId = intent.getIntExtra(Constant.PENPAL_ID, 0);
        }
        setPresenter(new SubmitPostPresenter(this), this);
        pictrues = new ArrayList<>();
        postArticleImgAdapter = new PostArticleImgAdapter(this, pictrues);
        pictureList.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        pictureList.setAdapter(postArticleImgAdapter);
        MyCallBack myCallBack = new MyCallBack(postArticleImgAdapter, pictrues);
        itemTouchHelper = new ItemTouchHelper(myCallBack);
        itemTouchHelper.attachToRecyclerView(pictureList);//绑定RecyclerView
        //事件监听
        pictureList.addOnItemTouchListener(new OnRecyclerItemClickListener(pictureList) {

            @Override

            public void onItemClick(RecyclerView.ViewHolder vh) {
                Log.d("***********", pictrues.toString());
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                itemTouchHelper.startDrag(vh);
            }
        });
    }


    @Override
    protected void initData() {
        //加载历史草稿
        loadLocalDraft();
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @OnTextChanged(value = R.id.article_title, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void titleAfterTextChanged(Editable editable) {
        String msg = editable.toString();
        hintLayout.setVisibility(msg.length() == 0 ? View.VISIBLE : View.GONE);
    }

    @OnTextChanged(value = R.id.article_content, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void contentAfterTextChanged(Editable editable) {
        String msg = editable.toString();
        int length = msg.length();
        contentLength.setText(TextUtils.isEmpty(msg) ? "0/500" : length + "/500");
        if (length == 500) {
            toast("最多只能输⼊500字符");
        }
    }

    @OnClick({R.id.head_left, R.id.head_right, R.id.add_image, R.id.add_post_title})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_left:
                onBackPressed();
                break;
            case R.id.head_right:
                if (TextUtils.isEmpty(articleContent.getText().toString())) {
                    ToastUtils.show("您还没有编辑内容");
                } else {
                    showKeyboard(false);
                    showLoading(true);
                    if (pictrues != null && pictrues.size() > 0) {
                        //如果有插图：1、先把图片上传
                        LogUtil.d("待上传的图片集合" + pictrues.toString());
                        presenter.pictureDealWith(pictrues);
                    } else {
                        //如果无插图：2、直接提交内容
                        uploadPictureSuccess(null);
                    }

                }
                break;
            case R.id.add_image:
                if (pictrues.size() >= IMAGE_SIZE) {
                    toast("最多能上传9张图片");
                } else {
                    presenter.getPicture(REQUEST_PICTURE_CODE, IMAGE_SIZE - pictrues.size());
                }
                break;
            case R.id.add_post_title:
                showArticleTitle = !showArticleTitle;
                articleTitleLayout.setVisibility(showArticleTitle ? View.VISIBLE : View.GONE);
                addPostTitle.setText(showArticleTitle ? "隐藏标题" : "显示标题");
                if (showArticleTitle) {
                    articleTitle.requestFocus();
                    articleTitle.setFocusable(true);
                    articleTitle.setFocusableInTouchMode(true);
                } else {
                    articleContent.requestFocus();
                    articleContent.setFocusable(true);
                    articleContent.setFocusableInTouchMode(true);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_PICTURE_CODE) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                for (int index = 0; index < selectList.size(); index++) {
                    pictrues.add(selectList.get(index).getCompressPath());
                }
                postArticleImgAdapter.notifyDataSetChanged();
            }
        }
    }

    //加载本地保存的帖子草稿
    private void loadLocalDraft() {
        String localDraftTitle = SPUtils.getPreferences(SPKey.POST_DRAFT_TITLE, "");
        String localDraftContent = SPUtils.getPreferences(SPKey.POST_DRAFT_CONTENT, "");
        if (!TextUtils.isEmpty(localDraftTitle)) {
            articleTitle.setText(localDraftTitle);
            hintLayout.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(localDraftContent)) {
            articleContent.setText(localDraftContent);
        }
        initialTitle = articleTitle.getText().toString();
        initialContent = articleContent.getText().toString();
    }

    @Override
    public void onBackPressed() {
        PictureFileUtils.deleteCacheDirFile(this);
        String currentTitle = articleTitle.getText().toString();
        String currentContent = articleContent.getText().toString();
        if (!TextUtils.equals(currentTitle, initialTitle)
                || !TextUtils.equals(currentContent, initialContent)) {//标题||内容，变更 且 未进行保存草稿
            presenter.showHintDialog(currentTitle, currentContent);
        } else {
            showKeyboard(false);
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    public void submitPostSuccess() {
        PictureFileUtils.deleteCacheDirFile(this);
        SPUtils.putPreferences(SPKey.POST_DRAFT_TITLE, "");
        SPUtils.putPreferences(SPKey.POST_DRAFT_CONTENT, "");
        showLoading(false);
        showKeyboard(false);
        finish();
    }

    @Override
    public void uploadPictureSuccess(List<String> upLoadImageList) {
        //帖子头图
        String postTopImg = "";
        //帖子插图
        String insertImgs = "";
        if (upLoadImageList != null) {
            //头图
            postTopImg = upLoadImageList.get(0);
            for (String img : upLoadImageList) {
                insertImgs = insertImgs + img + "|";
            }
        }
        //标题
        String postTitle = showArticleTitle ? articleTitle.getText().toString() : "";
        //内容
        String postContent = "";
        try {
            postContent = URLEncoder.encode(articleContent.getText().toString(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        presenter.postNote(postTitle, postContent, postTopImg, penpalId, insertImgs);
    }

    @Override
    public void finishActivity() {
        showKeyboard(false);
        finish();
    }
}
